// Simple reactive chat/friends store using Vue 3 reactivity and uni storage
import { reactive, computed } from 'vue'

const STORAGE_KEY = 'dy_chat_store_v2'
const STORE_VERSION = 2

function loadFromStorage() {
	try {
		const cached = uni.getStorageSync(STORAGE_KEY)
		if (cached && typeof cached === 'object') {
			return cached
		}
	} catch (e) {}
	return null
}

// Anime-style SVG avatars (offline, cute)
const bgColors = ['#FFE3ED','#E2F2FF','#E8F8E8','#FFF4D6','#EDE7FF','#FFEFE2']
const hairColors = ['#2B2B2B','#6B4F4F','#3B82F6','#F43F5E','#8B5CF6','#10B981']
const eyeColors = ['#111827','#1F2937','#0F172A']
function svgAnimeAvatar(seed = 0) {
	const bg = bgColors[Math.abs(seed) % bgColors.length]
	const hair = hairColors[Math.abs(seed + 3) % hairColors.length]
	const eye = eyeColors[Math.abs(seed + 5) % eyeColors.length]
	// 可爱嘴型（猫嘴/微笑/嘟嘴）
	const mouth = [
		'M44 61 q4 6 8 0 q4 6 8 0',         // 可爱猫嘴
		'M44 62 q8 -4 16 0',                 // 微笑
		'M48 62 q4 -3 8 0'                   // 嘟嘴
	][Math.abs(seed+7)%3]
	const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='96' height='96' viewBox='0 0 96 96'>
<defs><linearGradient id='bg' x1='0' y1='0' x2='1' y2='1'><stop offset='0%' stop-color='${bg}'/><stop offset='100%' stop-color='#FFFFFF'/></linearGradient></defs>
<rect rx='48' ry='48' width='96' height='96' fill='url(#bg)'/>
<!-- hair -->
<path d='M12 38 q18 -28 36 -18 q18 -10 36 18 v26 h-72z' fill='${hair}'/>
<circle cx='30' cy='26' r='6' fill='${hair}'/>
<!-- face -->
<circle cx='48' cy='52' r='22' fill='#FFEADB'/>
<!-- eyes -->
<ellipse cx='39' cy='52' rx='5' ry='6' fill='${eye}'/>
<ellipse cx='57' cy='52' rx='5' ry='6' fill='${eye}'/>
<!-- eye highlight -->
<circle cx='37.5' cy='50' r='1.2' fill='#FFFFFF' opacity='0.9'/>
<circle cx='55.5' cy='50' r='1.2' fill='#FFFFFF' opacity='0.9'/>
<!-- blush -->
<ellipse cx='33' cy='60' rx='6' ry='2.6' fill='#FFB3C7' opacity='0.6'/>
<ellipse cx='63' cy='60' rx='6' ry='2.6' fill='#FFB3C7' opacity='0.6'/>
<!-- mouth -->
<path d='${mouth}' stroke='#E11D48' stroke-width='2' fill='none' stroke-linecap='round'/>
<!-- sparkle -->
<path d='M72 30 l2 4 l4 2 l-4 2 l-2 4 l-2 -4 l-4 -2 l4 -2 z' fill='#FDE68A' opacity='0.9'/>
</svg>`;
	return 'data:image/svg+xml;utf8,' + encodeURIComponent(svg)
}
function getRandomAvatar(name = '') {
	const seed = (name && Array.from(name)[0]?.codePointAt(0)) || Math.floor(Math.random()*10000)
	return svgAnimeAvatar(seed)
}

// Specific cute sunflower avatar for self
function svgSunflowerAvatar() {
	const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='96' height='96' viewBox='0 0 96 96'>
<defs><linearGradient id='bg' x1='0' y1='0' x2='1' y2='1'><stop offset='0%' stop-color='#FFF7CC'/><stop offset='100%' stop-color='#FFE4B5'/></linearGradient></defs>
<rect rx='48' ry='48' width='96' height='96' fill='url(#bg)'/>
<!-- petals -->
<g fill='#F59E0B'>
  <circle cx='48' cy='20' r='10'/>
  <circle cx='67' cy='25' r='10'/>
  <circle cx='76' cy='42' r='10'/>
  <circle cx='67' cy='59' r='10'/>
  <circle cx='48' cy='64' r='10'/>
  <circle cx='29' cy='59' r='10'/>
  <circle cx='20' cy='42' r='10'/>
  <circle cx='29' cy='25' r='10'/>
</g>
<!-- center face -->
<circle cx='48' cy='42' r='18' fill='#8B5E3C'/>
<circle cx='42' cy='40' r='3' fill='#111'/>
<circle cx='54' cy='40' r='3' fill='#111'/>
<path d='M40 46 q8 6 16 0' stroke='#FFB3C7' stroke-width='2' fill='none' stroke-linecap='round'/>
</svg>`
	return 'data:image/svg+xml;utf8,' + encodeURIComponent(svg)
}

const initialState = loadFromStorage() || {
	friends: [
		{ id: 'u_1', name: 'zcc', avatar: getRandomAvatar('zcc'), pinned: false },
		{ id: 'u_2', name: 'cc', avatar: getRandomAvatar('cc'), pinned: false },
		{ id: 'u_3', name: '是cc啊', avatar: getRandomAvatar('是cc啊'), pinned: false }
	],
	conversations: {
		// id -> { messages:[{id,from,to,content,timestamp}], unread:number }
	},
	self: { id: 'me', name: '我', avatar: svgSunflowerAvatar() },
	version: STORE_VERSION
}

const state = reactive(initialState)

function persist() {
	try {
		uni.setStorageSync(STORAGE_KEY, JSON.parse(JSON.stringify(state)))
	} catch (e) {}
}

// Migration to ensure sunflower avatar and versioned storage
(function migrate() {
	try {
		if (!state.version || state.version < STORE_VERSION) {
			// Force self avatar to sunflower for this version
			state.self = state.self || { id: 'me', name: '我' }
			state.self.avatar = svgSunflowerAvatar()
			state.version = STORE_VERSION
			persist()
		}
	} catch (e) {}
})()
function ensureConv(friendId) {
	if (!state.conversations[friendId]) {
		state.conversations[friendId] = { messages: [], unread: 0 }
	}
	return state.conversations[friendId]
}

export const friends = computed(() => state.friends)
export const selfUser = computed(() => state.self)

export function addFriend(name, avatar) {
	const id = 'u_' + Date.now()
	state.friends.unshift({
		id,
		name,
		avatar: avatar || getRandomAvatar(name),
		pinned: false
	})
	ensureConv(id)
	persist()
	return id
}

export function deleteFriend(friendId) {
	const idx = state.friends.findIndex(f => f.id === friendId)
	if (idx !== -1) {
		state.friends.splice(idx, 1)
		delete state.conversations[friendId]
		persist()
	}
}

export function sendMessage(toId, content) {
	const conv = ensureConv(toId)
	const msg = { id: 'm_' + Date.now(), from: state.self.id, to: toId, content, timestamp: Date.now() }
	conv.messages.push(msg)
	persist()
	return msg
}

export function receiveMessage(fromId, content) {
	const conv = ensureConv(fromId)
	const msg = { id: 'm_' + Date.now(), from: fromId, to: state.self.id, content, timestamp: Date.now() }
	conv.messages.push(msg)
	conv.unread += 1
	persist()
	return msg
}

export function getConversation(friendId) {
	return ensureConv(friendId)
}

export function clearUnread(friendId) {
	const conv = ensureConv(friendId)
	conv.unread = 0
	persist()
}

export function unreadTotal() {
	return Object.values(state.conversations).reduce((sum, c) => sum + (c.unread || 0), 0)
}

export function findFriendById(friendId) {
	return state.friends.find(f => f.id === friendId)
}


